package com.axend.aerosense.pay.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.utils.LogUtils;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.UserInfo;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.ui.WebActivity;
import com.axend.aerosense.common.util.DateUtil;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.pay.BR;
import com.axend.aerosense.pay.R;
import com.axend.aerosense.pay.databinding.PayVipHomeFragmentBinding;
import com.axend.aerosense.pay.entity.PayCompleteBean;
import com.axend.aerosense.pay.entity.PayModeBean;
import com.axend.aerosense.pay.entity.VipCenterContentBean;
import com.axend.aerosense.pay.entity.VipMoneyCardBean;
import com.axend.aerosense.pay.entity.VipUserBean;
import com.axend.aerosense.pay.ui.PayHomeActivity;
import com.axend.aerosense.pay.ui.adapter.PayVipModeAdapter;
import com.axend.aerosense.pay.ui.adapter.PayVipMoneyCardAdapter;
import com.axend.aerosense.pay.viewmodel.VipHomeViewModel;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;

public class PayVipHomeFragment extends MvvmBaseFragment<PayVipHomeFragmentBinding, VipHomeViewModel>
        implements ILoadDataResult<VipCenterContentBean> {

    private PayVipMoneyCardAdapter payVipMoneyCardAdapter;
    private PayVipModeAdapter payVipModeAdapter;
    private VipCenterContentBean vipCenterContentBean;
    private VipUserBean vipUserBean;
    private long clickTime = 0;

    private IOperationResult operationResult = new IOperationResult() {
        @Override
        public void onSuccess() {
            viewModel.onLoad();
        }

        @Override
        public void onFail() {
            ToastUtils.showShort(R.string.pay_vip_failed);
        }
    };

    public void setVipUserBean(VipUserBean vipUserBean) {
        this.vipUserBean = vipUserBean;
        init();
    }

    public static PayVipHomeFragment getInstance() {
        return new PayVipHomeFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setLoadSir(viewDataBinding.payContentView);
        init();
        showLoading();
        viewModel.onLoad();

    }

    private void initTitle() {
        ((PayHomeActivity) getActivity()).setTitle(getString(R.string.pay_vip_title));
        ((PayHomeActivity) getActivity()).setTitleColor(Color.rgb(51, 51, 51));
        ((PayHomeActivity) getActivity()).setTitleBackground(Color.rgb(233, 233, 233));
        //((PayHomeActivity) getActivity()).getToolBar().setNavigationIcon(R.drawable.pay_ic_back_white);
    }

    @Override
    public void onResume() {
        super.onResume();
        ImmersionBar.with(getActivity())
                //#383838
                .statusBarColor("#e9e9e9")
                .navigationBarColor(android.R.color.transparent)
                .fitsSystemWindows(true)
//                            .titleBarMarginTop(R.id.topView)
                .autoDarkModeEnable(true)
                .init();
        initTitle();
    }

    public void initView(VipCenterContentBean vipCenterContentBean) {
        this.vipCenterContentBean = vipCenterContentBean;

        if (!TextUtils.isEmpty(vipCenterContentBean.getUserVipInfo().getUserVipEndTime()) && vipCenterContentBean.getUserVipInfo().getUserVipEndTime().length() >= 10) {
            String s = DateUtil.getEnglishDateFormatString2(vipCenterContentBean.getUserVipInfo().getUserVipEndTime().substring(0, 10));
            viewModel.dataTime.setValue(s);
        } else {
            viewModel.dataTime.setValue("");
        }
        viewModel.isVip.setValue(vipCenterContentBean.getUserVipInfo().getUserVipState() == Gobal.IntentParamType.VIP);
        setVipUserContext(viewModel.isVip.getValue());

        //价格卡片
        payVipMoneyCardAdapter = new PayVipMoneyCardAdapter();
        payVipMoneyCardAdapter.setData(vipCenterContentBean.getPayList());
        viewDataBinding.payRecyclerMoneyCard.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
        viewDataBinding.payRecyclerMoneyCard.setAdapter(payVipMoneyCardAdapter);

        //会员规则
        viewDataBinding.payProtocolTv.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra(WebActivity.URL, vipCenterContentBean.getMemberServices());
            intent.putExtra(WebActivity.TITLE, getString(R.string.pay_vip_service_rules));
            startActivity(intent);
        });

        //帮助
        viewDataBinding.payHelp.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra(WebActivity.URL, UrlApi.helpUrl);
            intent.putExtra(WebActivity.TITLE, getString(R.string.user_helpv));
            getActivity().startActivity(intent);
        });

        UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
        viewDataBinding.payCardVipNumTv.setText(userInfo.userEmail);

        if (viewModel.autoRenew.getValue() != null) {
            viewDataBinding.payAutoFeeCheckbox.setChecked(viewModel.autoRenew.getValue());
        } else {
            viewDataBinding.payAutoFeeCheckbox.setChecked(false);
        }
        viewDataBinding.payAutoFeeCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            viewModel.autoRenew.postValue(isChecked);
        });

        //支付方式
        payVipModeAdapter = new PayVipModeAdapter();
        payVipModeAdapter.setData(vipCenterContentBean.getPayType());
        viewDataBinding.payModeRecycler.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        viewDataBinding.payModeRecycler.setAdapter(payVipModeAdapter);

        viewModel.autoRenew.removeObservers(getViewLifecycleOwner());
        //自动续费
        viewModel.autoRenew.observe(getViewLifecycleOwner(), aBoolean -> {
            payVipMoneyCardAdapter.setAutoPay(aBoolean);
        });

        //点击支付
        viewDataBinding.payButton.setOnClickListener(v -> {
            long tmp = System.currentTimeMillis();
            if(tmp - clickTime < 3000){
                return;
            }else{
                clickTime = tmp;
            }

            PayModeBean payModeBean = payVipModeAdapter.getSelectItemBean();
            VipMoneyCardBean vipMoneyCardBean = payVipMoneyCardAdapter.getSelectItemBean();

            if (null != vipMoneyCardBean && null != payModeBean){
                viewModel.vipPay(getActivity(), vipMoneyCardBean, payModeBean, operationResult);
            }else {
                ToastUtils.showShort(R.string.pay_select_pay_type);
            }
        });
    }

    public void init() {
        viewDataBinding.payPurchaseRecordTv.setOnClickListener(v -> {
            Fragment fragment = PayPurchaseRecordFragment.getInstance();
            try{
                FragmentUtil.add(getActivity(), ((PayHomeActivity) getActivity()).getContentId(), fragment, this, true);
            }catch (Exception e){
                e.printStackTrace();
            }

        });
        if (vipUserBean != null) {
            viewModel.isVip.setValue(vipUserBean.getUserVipState() == Gobal.IntentParamType.VIP);
            String s = DateUtil.getEnglishDateFormatString2(vipUserBean.getUserVipEndTime());
            viewModel.dataTime.setValue(s);
        }
    }

    /**
     * 设置显示是否是vip
     *
     * @param isVip 是否是会员
     */
    private void setVipUserContext(boolean isVip) {
        if (isVip) {
            LogUtils.d("myTAG", "setVipUserContext: true,设置了");

            viewDataBinding.payCardVipTv.setText(R.string.pay_vip_card);
            viewDataBinding.payCardVipValidityTv.setText(R.string.pay_vip_period);
            viewDataBinding.payCardVipTimeTv.setText(viewModel.dataTime.getValue());
            viewDataBinding.payVipContextCard.setBackground(ContextCompat.getDrawable(getContext(), R.mipmap.pay_card_bg_1));
        } else {
            LogUtils.d("myTAG", "setVipUserContext: false,设置了");

            viewDataBinding.payCardVipTv.setText(R.string.pay_vip_card_false);
            viewDataBinding.payCardVipValidityTv.setText(R.string.pay_vip_period_false);
            viewDataBinding.payCardVipTimeTv.setText("");
            viewDataBinding.payVipContextCard.setBackground(ContextCompat.getDrawable(getContext(), R.mipmap.pay_card_bg_2));
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.pay_vip_home_fragment;
    }

    @Override
    public int getBindingVariable() {
        return BR.viewmodel;
    }

    @Override
    protected VipHomeViewModel getViewModel() {
        BaseViewModelFactroy<VipCenterContentBean> myViewModelFactory = new BaseViewModelFactroy<>(this, this);
        return new ViewModelProvider(this, myViewModelFactory).get(VipHomeViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void loadDataSuccess(VipCenterContentBean vipCenterContentBean) {
        initView(vipCenterContentBean);
    }

    @Override
    public void loadDataFail(String decs) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //viewModel.noticeCheckPayResult(getActivity(), viewModel.getOrderId(), PayCompleteBean.PAY_UNKOWN, operationResult, true);
    }
}
